package com.android.plc.ui.adapter;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.android.plc.provider.PLC;
import com.android.plc.util.StringUtil;

public class RoomCodeAdapter extends ArrayAdapter<String>
{
	private Context mContext;

	public RoomCodeAdapter(Context context, int item_id, String[] objects)
	{
		super(context, item_id, objects);
		mContext = context;
		ContentResolver resolver = context.getContentResolver();
		resolver.registerContentObserver(PLC.Rooms.CONTENT_URI, true,
				mContentObserver);
		initDisableList();
	}

	private ArrayList<String> mDisableList = new ArrayList<String>();

	public View getView(int position, View convertView, ViewGroup parent)
	{
		convertView = super.getView(position, convertView, parent);
		if (convertView instanceof TextView)
		{
			((TextView) convertView).setText(StringUtil.convRoomCode(mContext,
					position));
		}
		return convertView;
	}

	public int findFirstAvailableCode()
	{
		int size = getCount();
		for (int i = 0; i < size; i++)
		{
			String code = getItem(i);
			if (mDisableList.contains(code))
			{
				continue;
			}
			return i;
		}
		return -1;
	}

	public void initDisableList()
	{
		mDisableList.clear();
		ContentResolver resolver = mContext.getContentResolver();
		Cursor cursor = resolver.query(PLC.Rooms.CONTENT_URI,
				PLC.ROOMS_PROJECTION, null, null, null);
		while (cursor.moveToNext())
		{
			String code = StringUtil.convCode(cursor.getInt(2));
			if (!mDisableList.contains(code))
			{
				mDisableList.add(code);
			}
		}
		cursor.close();
	}

	public void setDisableList(ArrayList<String> disableList)
	{
		this.mDisableList.clear();
		for (String code : disableList)
		{
			if (mDisableList.contains(code))
			{
				continue;
			}
			mDisableList.add(code);
		}
	}

	public ArrayList<String> getDisableList()
	{
		return mDisableList;
	}

	private ContentObserver mContentObserver = new ContentObserver(
			new Handler())
	{
		@Override
		public void onChange(boolean selfChange)
		{
			initDisableList();
			notifyDataSetChanged();
		}
	};
}